extends Control

@export var host = '127.0.0.1'
@export var port = 8910

@onready var input: LineEdit = $LineEdit

var peer: ENetMultiplayerPeer

func _ready():
	# 连接信号
	multiplayer.peer_connected.connect(playerConnected)
	multiplayer.peer_disconnected.connect(playerDisconnected)
	multiplayer.connected_to_server.connect(connected)
	multiplayer.connection_failed.connect(disconnected)
	# 当启动为服务器时自动创建大厅
	if "--server" in OS.get_cmdline_args():
		createHall()
		
# 服务端事件--> 每当有玩家连接时事件触发
# 玩家连接
func playerConnected(id):
	print('新玩家加入:' + str(id))
# 玩家断开
func playerDisconnected(id):
	print('玩家离开:' + str(id))
	Game.players.erase(id)
	var players = get_tree().get_nodes_in_group('Player')
	for i in players:
		if i.name == str(id):
			i.queue_free()

# 客户端事件--> 本地客户端连接事件触发
# 本地连接
func connected():
	print('已加入大厅')
	# 本地连接后，分发玩家信息
	sendPlayerMsg.rpc_id(1, multiplayer.get_unique_id(), input.text)
# 本地断开
func disconnected():
	print('已离开大厅')

# 同步玩家信息
@rpc("any_peer")
func sendPlayerMsg(id, msg):
	if !Game.players.has(id): Game.players[id] = {
		"id": id,
		"name": msg,
		"score": 0
	}

	# 向所有人分发玩家信息
	if multiplayer.is_server():
		for key in Game.players:
			var player = Game.players[key]
			sendPlayerMsg. rpc (key, player.name)

# 使用rpc注解，所有人可以访问
@rpc("any_peer", "call_local")
func startGame() -> void:
	var scene = load('res://场景/main.tscn').instantiate()
	get_tree().root.add_child(scene)
	self.hide()

# 创建大厅
func createHall() -> void:
	peer = ENetMultiplayerPeer.new()
	# 最多32人连接
	var error = peer.create_server(port, 2)
	if error != OK:
		print('创建大厅失败:' + str(error))
		return
	# 信息的压缩算法设置
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)

	multiplayer.set_multiplayer_peer(peer)
	print('创建大厅成功，等待玩家连接')

# 创建大厅同步数据
func _on_host_button_down():
	createHall()
	sendPlayerMsg(multiplayer.get_unique_id(), input.text)
	
# 加入大厅
func _on_join_button_down():
	peer = ENetMultiplayerPeer.new()
	peer.create_client(host, port)
	peer.get_host().compress(ENetConnection.COMPRESS_RANGE_CODER)
	multiplayer.set_multiplayer_peer(peer)

# 开始游戏
func _on_start_game_button_down():
	startGame.rpc()
